<?php
/**
 * 用户数据管理
 * @author JohnnyDen <413819942@qq.com>
 * @package app\controller
 * @copyright 2018年11月12日
 */
namespace app\controller;

use api\Api;

class User extends Api {
    
    //授权用户验证
    protected $authUserMethods      = true;
    
    /**
     * 获取用户帐号和动态密码，用于模拟Form表单登录
     */
    public function getAccountDynamicPasswd() {
        $id_xpp_user        = in('id_xpp_user/d');
        $dynamic_passwd     = \think\helper\Str::random(24);
        if (!$dynamic_passwd) {
            out('exe_fail');
        }
        $md5_dynamic_passwd = create_md5($dynamic_passwd, $this->user('salt'));
        
        $res = db('Users')->where('uid', $this->user('uid'))->update([
            'dynamic_passwd'    => $md5_dynamic_passwd,
            'login_id_xpp_user' => $id_xpp_user,
        ]);
        if (false === $res) {
            out('exe_fail');
        }
        
        out('ok', [
            'username'          => $this->user('username'),
            'dynamic_passwd'    => $dynamic_passwd,
        ]);
    }
    
    /**
     * 获取用户信息
     */
    public function getAccount() {
        $user   = db('Users')->field('username,nickname,view_pwd')->where('uid', $this->user('uid'))->find();
        
        out('ok', $user);
    }
    
    /**
     * 修改帐号信息
     */
    public function saveAccount() {
        $nickname   = in('nickname');
        $password   = in('password');
        
        if (!$nickname) {
            out('empty_nickname');
        }
        
        $data   = array(
            'nickname'  => $nickname,
        );
        
        if($password) {
            $data['view_pwd']   = $password;
            $data['salt']       = create_salt(8);
            $data['password']   = create_md5(md5($password), $data['salt']);
        }
        $result = db('Users')->where('uid', $this->user('uid'))->update($data);
        if (false === $result) {
            out('exe_fail');
        }
        
        out('ok');
    }
}